import { MessageBox, Message, Notification } from 'element-ui'
import {} from '.'

export function showNotice(type, title, msg) {
  Notification({
    title: title,
    message: msg || type,
    offset: 500,
    duration: 1500,
    type: type,
    position: 'bottom-right'
  })
}
export function showMsgNotice(type, title, msg, onClick) {
  Notification({
    title: title,
    message: msg || type,
    offset: 100,
    duration: 4500,
    type: type,
    onClick: onClick,
    position: 'bottom-right'
  })
}
export function successNotice() {
  Notification({
    title: '提示',
    message: '这是一条操作成功的提示消息',
    offset: 300,
    duration: 1500,
    type: 'success'
  })
}

export function dateFormat(fmt, date) {
  let ret
  const opt = {
    'Y+': date.getFullYear().toString(), // 年
    'm+': (date.getMonth() + 1).toString(), // 月
    'd+': date.getDate().toString(), // 日
    'H+': date.getHours().toString(), // 时
    'M+': date.getMinutes().toString(), // 分
    'S+': date.getSeconds().toString() // 秒
  }
  for (const k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt)
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
    }
  }
  return fmt
}

export function formatDateTime() {
  var date = new Date()
  var y = date.getFullYear()
  var m = date.getMonth() + 1
  m = m < 10 ? ('0' + m) : m
  var d = date.getDate()
  d = d < 10 ? ('0' + d) : d
  var h = date.getHours()
  h = h < 10 ? ('0' + h) : h
  var minute = date.getMinutes()
  var second = date.getSeconds()
  minute = minute < 10 ? ('0' + minute) : minute
  second = second < 10 ? ('0' + second) : second
  return {
    'ymd': y + '-' + m + '-' + d,
    'ymdhm': y + '-' + m + '-' + d + ' ' + h + ':' + minute

  }
}

export function checkMobile(mobile) {
  mobile = mobile.toString()
  var index1 = mobile.substring(0, 1)
  var index2 = mobile.substring(0, 2)
  if (index2 == '11' || index2 == '12' || index1 !== '1' || mobile.length !== 11) {
    return false
  } else {
    return true
  }
}
export function checkBlank(info, tip) {
  if (info === '') {
    showNotice('error', '提示', tip)
    return false
  }
}

export function toTreeData(data, attributes) {
  const resData = data
  const tree = []
  for (let i = 0; i < resData.length; i++) {
    if (resData[i].parentId === attributes.rootId) {
      const obj = {
        id: resData[i][attributes.id],
        title: resData[i][attributes.name],
        children: []
      }
      tree.push(obj)
      resData.splice(i, 1)
      i--
    }
  }

  run(tree)
  function run(chiArr) {
    if (resData.length !== 0) {
      for (let i = 0; i < chiArr.length; i++) {
        for (let j = 0; j < resData.length; j++) {
          if (chiArr[i].id === resData[j][attributes.parentId]) {
            const obj = {
              id: resData[j][attributes.id],
              title: resData[j][attributes.name],
              children: []
            }
            chiArr[i].children.push(obj)
            resData.splice(j, 1)
            j--
          }
        }
        run(chiArr[i].children)
      }
    }
  }
  return tree
}

export function bubbleSort(list) {
  for (var i = 0; i < list.length - 1; i++) {
    for (var j = 0; j < list.length - 1 - j; j++) {
      if (list[j].sort > list[j + 1].sort) {
        var temp = list[j]
        list[j] = list[j + 1]
        list[j + 1] = temp
      }
    }
  }
  // console.log(list)
}
export function transData(list, idstr, pidstr) {
  // console.log(list)
  bubbleSort(list)
  // console.log('list======', list)
  // console.log('idstr======', idstr)
  // console.log('pidstr======', pidstr)
  var result = []; var temp = {}
  // 创建一个对象 以每个元素的idstr建立索引
  for (var i = 0; i < list.length; i++) {
    temp[list[i][idstr]] = list[i]// 将nodes数组转成对象类型
  }
  for (var j = 0; j < list.length; j++) {
    var tempVp = temp[list[j][pidstr]] // 获取每一个子对象的父对象
    if (tempVp) { // 判断父对象是否存在，如果不存在直接将对象放到第一层
      if (!tempVp['children']) tempVp['children'] = []// 如果父元素的nodes对象不存在，则创建数组
      tempVp['children'].push(list[j])// 将本对象压入父对象的nodes数组
    } else {
      result.push(list[j])// 将不存在父对象的对象直接放入一级目录
    }
  }
  return result
}

export function GetUrlRelativePath(url) {
  var arrUrl = url.split('//')

  var start = arrUrl[1].indexOf('/')
  var relUrl = arrUrl[1].substring(start)

  if (relUrl.indexOf('?') !== -1) {
    relUrl = relUrl.split('?')[0]
  }
  return relUrl
}

export function randomString(len) {
  len = len || 32
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length
  var pwd = ''
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

// base64转成二进制
export function dataURItoBlob(dataurl) {
  var arr = dataurl.split(',')
  // 注意base64的最后面中括号和引号是不转译的
  var _arr = arr[1].substring(0, arr[1].length - 2)
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(_arr)
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], {
    type: mime
  })
}

// 图片Url转成Base64
export function convertImgToBase64(url, callback, outputFormat) {
  var canvas = document.createElement('CANVAS')
  var ctx = canvas.getContext('2d')
  var img = new Image()
  img.crossOrigin = 'Anonymous'
  img.onload = function() {
    canvas.height = img.height
    canvas.width = img.width
    ctx.drawImage(img, 0, 0)
    var dataURL = canvas.toDataURL(outputFormat || 'image/png')
    callback.call(this, dataURL)
    canvas = null
  }
  img.src = url
}

// base64 转 file 对象
export function dataURLtoFile(dataURL, fileName, fileType) {
  var arr = dataURL.split(',')
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, { type: fileType || 'image/jpg' })
}

